import router from '@/router'

const state = () => ({
  viewTabs: [],
  keepAlive: true,
})

const mutations = {
  CLEAR_VIEWTAB(state) {
    state.viewTabs = []
    router.push('/index')
  },
  ADD_VIEWTAB(state, viewTab) {
    let viewTabs = state.viewTabs
    let flag = false
    for (let i in viewTabs) {
      if (viewTabs[i].path == viewTab.path) {
        flag = true
        break
      }
    }

    if (!flag) {
      viewTabs.push(viewTab)
    }
  },
  DEL_VIEWTAB(state, path) {
    let viewTabs = state.viewTabs
    for (let i in viewTabs) {
      let viewTab = viewTabs[i]
      if (viewTab.path != path) {
        continue
      }

      viewTabs.splice(i, 1)

      if (router.currentRoute.value.path != path) {
        return
      }

      if (i == 0 && viewTabs.length == 0) {
        router.push('/index')
        return
      } else {
        viewTab = viewTabs[0]
      }

      router.push({
        name: viewTab.name,
        query: viewTab.query,
        params: viewTab.params,
      })
    }
  },
  SWITCH_KEEP_ALIVE(state) {
    state.keepAlive = !state.keepAlive
  },
}

const actions = {}

export default {
  namespaced: true,
  state: state,
  actions: actions,
  mutations: mutations,
}
